package com.example.administrator.base.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.administrator.base.application.App;
import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.bean.ReLogout;
import com.example.administrator.base.R;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.InputMethodUtil;
import com.example.administrator.base.util.SharedPreferencesUtils;


import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ResetPassword extends BaseActivity {

    @InjectView(R.id.Toolbar)
    Toolbar Toolbar;
    @InjectView(R.id.btn_next)
    Button btnNext;
    @InjectView(R.id.et_phone)
    EditText etPhone;
    @InjectView(R.id.et_code)
    EditText etCode;
    @InjectView(R.id.btn_code)
    Button btnCode;
    @InjectView(R.id.rl_Phone)
    RelativeLayout rlPhone;
    @InjectView(R.id.rl_Idcard)
    RelativeLayout rlIdcard;
    @InjectView(R.id.et_newphone)
    EditText etNewphone;
    @InjectView(R.id.et_name)
    EditText etName;
    @InjectView(R.id.et_idcard)
    EditText etIdcard;
    SweetAlertDialog sweetAlertDialog ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);
        ButterKnife.inject(this);
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("加载中");
        Intent intent = getIntent();
        String havephone = intent.getStringExtra("havephone");
        if (havephone.equals("0")) {
            rlIdcard.setVisibility(View.VISIBLE);
        } else if (havephone.equals("1")){
            rlPhone.setVisibility(View.VISIBLE);
        }
        etPhone.setFocusableInTouchMode(true);
        etPhone.requestFocus();
        InputMethodUtil.showInputMethod(etPhone, 998);
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("忘记密码");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals("")){
                    btnCode.setEnabled(true);
                }else {
                    btnCode.setEnabled(false);
                }
            }
        });
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                    if (!s.toString().equals("")){
                        btnNext.setEnabled(true);
                    }else {
                        btnNext.setEnabled(false);
                    }
            }
        });

    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }

    @OnClick({R.id.btn_next, R.id.btn_code,R.id.btn_next2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_next:
                String phone = etPhone.getText().toString();
                String code = etCode.getText().toString();
                sweetAlertDialog.show();
                SharedPreferencesUtils.setParam(ResetPassword.this,"phone", phone);
                RephoneAndcode(phone, code);
                break;
            case R.id.btn_code:
                String codephone =etPhone.getText().toString();
                sweetAlertDialog.show();
                getYzm(codephone);
                break;
            case R.id.btn_next2:
                if (etIdcard.getText().toString().equals("")){
                    Toast.makeText(ResetPassword.this,"身份证号不能为空",Toast.LENGTH_LONG).show();
                    return;
                }
                if (etNewphone.getText().toString().equals("")){
                    Toast.makeText(ResetPassword.this,"新手机号不能为空",Toast.LENGTH_LONG).show();
                    return;
                }if (etName.getText().toString().equals("")){
                Toast.makeText(ResetPassword.this,"姓名不能为空",Toast.LENGTH_LONG).show();
                return;
                }
                String newphone = etNewphone.getText().toString();
                String name = etName.getText().toString();
                String idcard = etIdcard.getText().toString();
                sweetAlertDialog.show();
                SharedPreferencesUtils.setParam(ResetPassword.this,"phone", newphone);
                ReIdcard(newphone, name, idcard);
                break;
        }
    }
    /*获取验证码*/
    public void getYzm(String phone) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "GETVERIFYCODE")
                .add("phone", phone)
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/system?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        if (mse!=null){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ResetPassword.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                sweetAlertDialog.dismiss();
                            }
                        });

                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ResetPassword.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }
                    } else {
                        throw new Exception("Unexpected code " + response);
                    }
                } catch (Exception e) {
                    sweetAlertDialog.dismiss();
                    e.printStackTrace();
                }
            }
        }).start();


    }
    /*验证验证码*/
    public void RephoneAndcode(final String phone, String code) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "VERIFICATIONOLDPHONECODE")
                .add("OldPhone", phone)
                .add("code",code)
                .build();

        final Request request = new Request.Builder()
                .url(App.getUrl())
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response ;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("789215",string);
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        if (mse.getCode()==1){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent=new Intent(ResetPassword.this,NewPassword.class);
                                    intent.putExtra("phone",phone);
                                    startActivity(intent);
                                    finish();
                                }
                            });
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ResetPassword.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                sweetAlertDialog.dismiss();
                            }
                        });

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /*验证身份*/
    public void ReIdcard(final String phone, String name, String id) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "FINDPSWNOPHONE")
                .add("phone", phone)
                .add("realName",name)
                .add("idCardnum",id)
                .build();

        final Request request = new Request.Builder()
                .url(App.getUrl())
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        if (mse.getCode()==1){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent=new Intent(ResetPassword.this,NewPassword.class);
                                    intent.putExtra("phone",phone);
                                    startActivity(intent);
                                    finish();
                                }
                            });

                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ResetPassword.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                sweetAlertDialog.dismiss();
                            }
                        });

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
